Skip to main content
Version: 16.10.0

utils

log

as_bytes

def as_bytes(file_: Union[bytes, bytearray, io.BytesIO])

Returns file_ as bytes.

Arguments:

  • file_ Union[bytes, bytearray, io.BytesIO] - The file

Returns:

bytes

Raises:

  • TypeError - If file_ is not an instance of: bytes, bytearray, io.BytesIO

as_io_BytesIO

def as_io_BytesIO(file_: Union[bytes, bytearray])

Returns file_ as io.BytesIO object.

Arguments:

  • file_ Union[bytes, bytearray] - The bytes or bytearray of the file

Returns:

io.BytesIO object

Raises:

  • TypeError - If file_ is not an instance of: bytes, bytearray, io.BytesIO

as_snake_case

def as_snake_case(string)

as_title

def as_title(string)

buffer_to_bytes

def buffer_to_bytes(buffer: ct.c_void_p, buffer_length: ct.c_size_t)

Convert ctypes buffer and buffer_length to bytes.

Arguments:

buffer (ct.c_void_p()): The file buffer. buffer_length (ct.c_size_t()): The file buffer length.

Returns:

  • bytes bytes - The file as bytes.

CwdHandler

class CwdHandler()

Changes the current working directory to new_cwd on enter, and back to previous cwd on exit.

Arguments:

  • new_cwd str - The new current working directory to temporarily change to.

__init__

def __init__(new_cwd: str)

__enter__

def __enter__()

__exit__

def __exit__(type, value, traceback)

delete_directory

def delete_directory(directory: str, keep_folder: bool = False)

Delete a directory and its contents.

Arguments:

  • directory str - The directory path.
  • keep_folder bool, optional - Default False. If False, only delete contents.

delete_empty_subdirectories

def delete_empty_subdirectories(directory: str)

Deletes all empty subdirectories of a given directory.

Arguments:

  • directory str - The directory to delete subdirectories from.

Returns:

None

flatten_list

def flatten_list(list_: Iterable)

Returns a flattened list. [[1, 2], ["3"], (4, 5,), [6]] --> [1, 2, "3", 4, 5, 6]

get_file_type

def get_file_type(file_path: str)

Returns the filetype of a file. "data/files/splat.zip" -> "zip"

get_libraries

def get_libraries(directory: str,
library_names: Optional[List[str]] = None,
ignore_errors: bool = False)

Recursively calls get_library on each library from glasswall.libraries.os_info on the given directory.

Arguments:

  • directory str - The directory to search from.
  • library_names List[str], optional - List of libraries to return, if None iterates all libraries found in glasswall.libraries.os_info
  • ignore_errors bool, optional - Default False, prevents get_library raising FileNotFoundError when True.

Returns:

  • libraries dict[str, str] - A dictionary of library names and their absolute file paths.

get_library

def get_library(library: str, directory: str)

Returns a path to the specified library found from the current directory or any subdirectory. If multiple libraries exist, returns the file with the latest modified time.

Arguments:

  • library str - The library to search for, ie: "rebuild", "word_search"
  • directory str - The directory to search from.

Returns:

  • library_file_path str - The absolute file path to the library.

Raises:

  • KeyError - Unsupported OS or library name was not found in glasswall.libraries.os_info.
  • FileNotFoundError - Library was not found.

iterate_directory_entries

def iterate_directory_entries(directory: str,
file_type: str = 'all',
absolute: bool = True,
recursive: bool = True,
followlinks: bool = True,
start_directory: str = None)

Generate entries (files, directories, or both) in a given directory using os.scandir().

Arguments:

  • directory str - The path to the directory whose entries are to be listed.
  • file_type str, optional - Type of entries to return.
    • 'all': Return both files and directories (default).
    • 'files': Return only files.
    • 'directories': Return only directories.
  • absolute bool, optional - Whether to return absolute paths (default) or relative paths.
  • recursive bool, optional - Whether to recurse into subdirectories (default is True).
  • followlinks bool, optional - Whether to follow symbolic links and yield entries from the target directory (default is True).
  • start_directory str, optional - The starting directory used to calculate relative paths (default is None).

Yields:

  • str - The full path of each file or directory found in the specified directory.

Raises:

  • ValueError - If an invalid 'file_type' value is provided.
  • NotADirectoryError - If the directory does not exist.

Example:

directory = '/path/to/your/directory'

Iterate through all entries (files and directories) in the directory

for entry in iterate_directory_entries(directory): print(entry)

Iterate through only file entries in the directory

for file in iterate_directory_entries(directory, file_type='files'): print("File:", file)

Iterate through only directory entries in the directory

for directory in iterate_directory_entries(directory, file_type='directories'): print("Directory:", directory)

list_file_paths

def list_file_paths(directory: str,
file_type: str = 'files',
absolute: bool = True,
recursive: bool = True,
followlinks: bool = True) -> list

List all file paths in a given directory and its subdirectories.

Arguments:

  • directory str - The path to the directory whose file paths are to be listed.
  • file_type str, optional - Type of entries to return.
    • 'all': Return both files and directories.
    • 'files': Return only files (default).
    • 'directories': Return only directories.
  • absolute bool, optional - Whether to return absolute paths (default is True).
  • recursive bool, optional - Whether to recurse into subdirectories (default is True).
  • followlinks bool, optional - Whether to follow symbolic links and list file paths from the target directory (default is True).

Returns:

  • list - A list of file paths found in the specified directory and its subdirectories.

Example:

directory = '/path/to/your/directory' file_paths = list_file_paths(directory) print(file_paths)

list_subdirectory_paths

def list_subdirectory_paths(directory: str,
recursive: bool = False,
absolute: bool = True)

Returns a list of paths to subdirectories in a directory.

Arguments:

  • directory str - The directory to list subdirectories from.
  • recursive bool, optional - Default False. Include subdirectories of subdirectories.
  • absolute bool, optional - Default True. Return paths as absolute paths. If False, returns relative paths.

Returns:

  • subdirectories list - A list of subdirectory paths.

load_dependencies

def load_dependencies(dependencies: list, ignore_errors: bool = False)

Calls ctypes.cdll.LoadLibrary on each file path in dependencies.

Arguments:

  • dependencies list - A list of absolute file paths of library dependencies.
  • ignore_errors bool, optional - Default False, avoid raising exceptions from ct.cdll.LoadLibrary if ignore_errors is True.

Returns:

  • missing_dependencies list - A list of missing dependencies, or an empty list.

round_up

def round_up(number: float, decimals=0) -> float

Rounds a number up to a specified number of decimal places.

Arguments:

  • number float - The number to be rounded.
  • decimals int, optional - The number of decimal places to round to. Defaults to 0.

Returns:

  • float - The rounded number.

Examples:

>>> round_up(105, 0) 105.0 >>> round_up(0.015, 2) 0.02 >>> round_up(0.025, 2) 0.03 >>> round_up(0.00001, 2) 0.01

TempDirectoryPath

class TempDirectoryPath()

Gives a path to a uniquely named temporary directory that does not currently exist on enter, deletes the directory if it exists on exit.

Arguments:

  • delete bool, optional - Default True. Delete the temporary directory on exit

__init__

def __init__(delete: bool = True)

__enter__

def __enter__()

__exit__

def __exit__(type, value, traceback)

TempFilePath

class TempFilePath()

Gives a path to a uniquely named temporary file that does not currently exist on enter, deletes the file if it exists on exit.

Arguments:

  • directory Union[str, None], optional - The directory to create a temporary file in.
  • delete bool, optional - Default True. Delete the temporary file on on exit

__init__

def __init__(directory: Union[str, None] = None, delete: bool = True)

__enter__

def __enter__()

__exit__

def __exit__(type, value, traceback)

validate_xml

def validate_xml(
xml: Union[str, bytes, bytearray, io.BytesIO,
"glasswall.content_management.policies.policy.Policy"])

Attempts to parse the xml provided, returning the xml as string. Raises ValueError if the xml cannot be parsed.

Arguments:

  • xml Union[str, bytes, bytearray, io.BytesIO, glasswall.content_management.policies.policy.Policy] - The xml string, or file path, bytes, or ContentManagementPolicy instance to parse.

Returns:

  • xml_string str - A string representation of the xml.

Raises:

  • ValueError - if the xml cannot be parsed.
  • TypeError - if the type of arg "xml" is invalid

xml_as_dict

def xml_as_dict(xml)

Converts a simple single-level xml into a dictionary.

Arguments:

  • xml Union[str, bytes, bytearray, io.BytesIO] - The xml string, or file path, or bytes to parse.

Returns:

  • dict_ dict - A dictionary of element tag : text

deprecated_alias

def deprecated_alias(**aliases: str) -> Callable

Decorator for deprecated function and method arguments.

Use as follows:

@deprecated_alias(old_arg='new_arg') def myfunc(new_arg): ...

https://stackoverflow.com/a/49802489

rename_kwargs

def rename_kwargs(func_name: str, kwargs: Dict[str, Any], aliases: Dict[str,
str])

Helper function for deprecating function arguments.

https://stackoverflow.com/a/49802489

deprecated_function

def deprecated_function(replacement_function)